package com.example.androidautoproject.utils

import android.accessibilityservice.AccessibilityService
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo

private fun CharSequence?.default(): String {
    return this?.toString() ?: ""
}

private fun String?.default(): String {
    return this ?: ""
}

data class NodeWrapper(
    var className: String,
    var text: String? = null,
    var id: String? = null,
    var description: String? = null,
    var isClickable: Boolean = false,
    var isScrollable: Boolean = false,
    var isEditable: Boolean = false,
    var nodeInfo: AccessibilityNodeInfo? = null
){
    override fun toString(): String {
        return "className = $className → text = $text → id = $id → description = $description → isClickable = $isClickable → isScrollable = $isScrollable → isEditable = $isEditable"
    }
}


fun AccessibilityNodeInfo?.printNodeInfo(prefix: String = "", isLast: Boolean = false){
    val node = this?:return
    val nodeWrapper = NodeWrapper(
        className = node.className.default(),
        text = node.text.default(),
        id = node.viewIdResourceName.default(),
        description = node.contentDescription.default(),
        isClickable = node.isClickable,
        isScrollable = node.isScrollable,
        isEditable = node.isEditable,
        nodeInfo = node
    )
    val marker = if(isLast) """\--- """ else "+--- "
    var currentPrefix = "$prefix$marker"
    //打印我们需要的信息
    Log.d("printNodeInfo", currentPrefix + nodeWrapper.toString())
    val size = node.childCount
    if(size > 0){
        var childPrefix = prefix + if(isLast) "  " else "|  "
        val lastChildIndex = size - 1
        for(index in 0 until size){
            var isLastChild = index === lastChildIndex
            node.getChild(index).printNodeInfo(childPrefix, isLastChild)
        }
    }
}
fun AccessibilityService?.printNodeInfo(){
    this ?: return
    rootInActiveWindow.printNodeInfo()
}